package com.irate.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.irate.adapter.RatingCategoryAdapter;
import com.irate.dao.RatingCategoryDAO;
import com.irate.http.AsyncHttpResponseHandler;
import com.irate.model.RatingCategory;
import com.irate.provider.ContentManager;

public class ListCategoryActivity extends Activity {

	protected ListView lv;
	protected Button okbut;
	protected Button addMoreCategory;
	protected View contentView;
	protected View mainView;
	protected RatingCategoryDAO rdao;
	protected ProgressDialog dialog;
	protected RelativeLayout rl;
	protected String category_new_name = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		LayoutInflater inflat = LayoutInflater.from(this);
		mainView = inflat.inflate(R.layout.popup_list_category, null);
		setContentView(mainView);
		init();
		execute();

	}

	private void init() {
		rl = (RelativeLayout) mainView
				.findViewById(R.id.content_category_popup);
		lv = (ListView) findViewById(R.id.list_content_category);
		okbut = (Button) findViewById(R.id.addCategoryOK);
		addMoreCategory = (Button) findViewById(R.id.addCategoryAddMore);
		LayoutInflater inflat = LayoutInflater.from(this);
		contentView = inflat.inflate(R.layout.popup_add_new_category, null);
		rdao = new RatingCategoryDAO();
	}

	private void execute() {

		RatingCategoryAdapter adapter = new RatingCategoryAdapter();

		lv.setAdapter(adapter);
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {

				int f = arg0.getFirstVisiblePosition();
				int l = arg0.getLastVisiblePosition();

				for (int i = 0; i <= l - f; i++) {
					View v = arg0.getChildAt(i);
					v.setBackgroundDrawable(getResources().getDrawable(
							R.drawable.category_item_background));
				}

				arg1.setBackgroundColor(Color.rgb(139, 137, 130));

				ContentManager.getInstance().setCategory_index_selected(arg2);
			}
		});

		okbut.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				RatingCategory str = (RatingCategory) lv
						.getItemAtPosition(ContentManager.getInstance()
								.getCategory_index_selected());

				if (str != ContentManager.getInstance().getRating_category()) {
					ContentManager.getInstance().setRating_category(str);
					ContentManager.getInstance().getListRatingCriteria()
							.clear();
				}
				onBackPressed();
			}
		});

		addMoreCategory.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				final PopupWindow pw = new PopupWindow(contentView,
						LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
						true);

				Button add_and_continute = (Button) contentView
						.findViewById(R.id.add_new_category_and_continute);

				final EditText et_new_category = (EditText) contentView
						.findViewById(R.id.new_category);
				final EditText et_sub_field1 = (EditText) contentView
						.findViewById(R.id.subfield1);
				final EditText et_sub_field2 = (EditText) contentView
						.findViewById(R.id.subfield2);
				final EditText et_criteria = (EditText) contentView
						.findViewById(R.id.criteria);
				final EditText et_criteria_op1 = (EditText) contentView
						.findViewById(R.id.criteria_op1);
				final EditText et_criteria_op2 = (EditText) contentView
						.findViewById(R.id.criteria_op2);

				add_and_continute.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {

						if (!et_new_category.getText().toString().trim()
								.equals("")
								&& !et_sub_field1.getText().toString().trim()
										.equals("")
								&& !et_sub_field2.getText().toString().trim()
										.equals("")
								&& !et_criteria.getText().toString().trim()
										.equals("")) {

							category_new_name = et_new_category.getText()
									.toString().trim();
							dialog = ProgressDialog.show(
									ListCategoryActivity.this, getResources()
											.getString(R.string.add_category),
									getResources().getString(R.string.loading),
									true);

							rdao.addNewCategory(handlerAddCategory,
									ListCategoryActivity.this, et_new_category
											.getText().toString(),
									et_sub_field1.getText().toString(),
									et_sub_field2.getText().toString(),
									et_criteria.getText().toString(),
									et_criteria_op1.getText().toString(),
									et_criteria_op2.getText().toString(),
									dialog);
						} else {
							Toast.makeText(ListCategoryActivity.this,
									getString(R.string.miss_information),
									Toast.LENGTH_SHORT).show();
						}

					}
				});

				pw.setBackgroundDrawable(new BitmapDrawable());
				pw.setAnimationStyle(android.R.style.Animation_Dialog);
				pw.showAtLocation(mainView, Gravity.CENTER, 0, 15);
				pw.setOnDismissListener(new OnDismissListener() {

					@Override
					public void onDismiss() {
						rl.setVisibility(View.VISIBLE);
					}
				});

				rl.setVisibility(View.INVISIBLE);

			}
		});

	}

	public void dimissWindow(View v) {
		onBackPressed();
	}

	public void clickNothing(View v) {
		// do nothing
	}

	AsyncHttpResponseHandler handlerAddCategory = new AsyncHttpResponseHandler() {
		@Override
		public void onSuccess(int statusCode, Header[] headers, byte[] response) {

			System.out.println("Success register");

			try {
				String str = new String(response);
				JSONObject obj = new JSONObject(str);

				RatingCategory rc = rdao.getData(obj.getString("message"));
				ContentManager.getInstance().getListRatingCategory().add(rc);
				ContentManager.getInstance().setRating_category(rc);
				ContentManager.getInstance().setCategory_index_selected(
						ContentManager.getInstance().getListRatingCategory()
								.size() - 1);
				
				onBackPressed();

			} catch (Exception ex) {

			}

			// rdao.getListCategory(handlerGetCategory,
			// ListCategoryActivity.this,
			// null);

		}

		@Override
		public void onStart() {
			System.out.println("Start");
		}

		@Override
		public void onFinish() {
			if (dialog != null)
				dialog.dismiss();
		}

		@Override
		public void onFailure(int statusCode, Header[] headers,
				byte[] errorResponse, Throwable e) {
			System.out.println("Fail Register");
			try {
				JSONObject obj = new JSONObject(new String(errorResponse));

				Toast.makeText(ListCategoryActivity.this,
						obj.getString("message").toString(), Toast.LENGTH_SHORT)
						.show();
			} catch (Exception ex) {

			}
		}
	};

	// AsyncHttpResponseHandler handlerGetCategory = new
	// AsyncHttpResponseHandler() {
	// @Override
	// public void onSuccess(int statusCode, Header[] headers, byte[] response)
	// {
	//
	// System.out.println("Success register");
	//
	// List<RatingCategory> lrc = new ArrayList<RatingCategory>();
	//
	// lrc = rdao.parseListData(new String(response));
	//
	// ContentManager.getInstance().setListRatingCategory(lrc);
	//
	// for (int i = 0; i < lrc.size(); i++) {
	// if (lrc.get(i).getCategory_name().equals(category_new_name)) {
	// ContentManager.getInstance().setRating_category(lrc.get(i));
	// ContentManager.getInstance().setCategory_index_selected(i);
	// break;
	// }
	// }
	//
	// }
	//
	// @Override
	// public void onStart() {
	// System.out.println("Start");
	// }
	//
	// @Override
	// public void onFinish() {
	// if (dialog != null)
	// dialog.dismiss();
	// onBackPressed();
	// }
	//
	// @Override
	// public void onFailure(int statusCode, Header[] headers,
	// byte[] errorResponse, Throwable e) {
	// System.out.println("Fail Register");
	// try {
	// JSONObject obj = new JSONObject(new String(errorResponse));
	//
	// Toast.makeText(ListCategoryActivity.this,
	// obj.getString("message").toString(), Toast.LENGTH_SHORT)
	// .show();
	// } catch (Exception ex) {
	// Toast.makeText(ListCategoryActivity.this,
	// getString(R.string.connection_error),
	// Toast.LENGTH_SHORT).show();
	// }
	// }
	// };

}
